const rob = root => {
  if (root === null) return 0
  const f = new Map(),
    g = new Map()

  const dfs = node => {
    if (node === null) return 0
    dfs(node.left)
    dfs(node.right)
    f.set(node, node.val + (g.get(node.left) || 0) + (g.get(node.right) || 0))
    g.set(node, Math.max(f.get(node.left) || 0, g.get(node.left) || 0) + Math.max(f.get(node.right) || 0, g.get(node.right) || 0))
  }
  dfs(root)
  return Math.max(f.get(root) || 0, g.get(root) || 0)
}

let root = {
  val: 3,
  left: {
    val: 2,
    left: null,
    right: {
      val: 3,
      left: null,
      right: null
    }
  },
  right: {
    val: 3,
    left: null,
    right: {
      val: 1,
      left: null,
      right: null
    }
  }
}

console.log(rob(root));